import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ribo_base_core/base_models/base_chart_model.dart';
import 'package:ribo_base_core/base_styles/base_chart_style.dart';
import 'package:flutter_echarts/flutter_echarts.dart';
import 'package:visibility_detector/visibility_detector.dart';

import 'themes/index.dart';

class BaseChart extends StatefulWidget {
  BaseChart({Key key, @required this.model}) : super(key: key);

  final BaseChartModel model;

  @override
  _BaseChartState createState() => _BaseChartState();
}

class _BaseChartState extends State<BaseChart> {
  Map<String, dynamic> _option;
  String _optionStr;
  dynamic _webController;
  bool _isVisible = false;

  @override
  Widget build(BuildContext context) {
    _handleModel();

    return VisibilityDetector(
        key: UniqueKey(),
        onVisibilityChanged: onVisibilityChanged,
        child: Echarts(
            extensions: [THEMES.SHINE]..addAll(widget.model?.extensions ?? []),
            theme: 'shine',
            onLoad: (dynamic controller) {
              _webController = controller;
            },
            extraScript: widget.model?.extraScript,
            onMessage: (str) {
              widget.model?.itemPress(str);
            },
            captureHorizontalGestures: true,
            option: _optionStr));
  }

  void onVisibilityChanged(VisibilityInfo info) {
    if (Platform.isIOS) {
      if (!_isVisible && info.visibleFraction > 0) {
        _isVisible = true;
        _webController?.reload();
      }
    }
  }

  void _handleModel() {
    _option = {
      ...BaseChartStyle().toJson(),
      ...widget.model?.option,
      ...widget.model?.style?.toJson() ?? {}
    };
    _option.removeWhere((key, value) => value == null);
    _optionStr = jsonEncode(_option);
    _optionStr =
        _optionStr.replaceAll('"@FUNCTION@', '').replaceAll('@FUNCTION@"', '');
  }
}
